package com.mfy.utils;

import com.mfy.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取到目标方法对象。
        if(handler instanceof HandlerMethod){
            //获取到了spring中对Method的封装
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            //把spring的Method转换为java反射中的Method
            Method method = handlerMethod.getMethod();
            //2.获取目标方法上面是否有RequiredToken注解。
            boolean annotationPresent = method.isAnnotationPresent(RequiredToken.class);
            //3.有注解，判断redis里面是否有登录标记。
            if(annotationPresent){
                //1.获取token信息
                String token = request.getParameter("token");
                //2.拼接前缀-+
                String tokenKey = RedisPrefix.USER_TOKEN_KEY + token;
                //3.根据tokenKey获取用户信息
                User o = (User) redisTemplate.opsForValue().get(tokenKey);
                if (o == null) throw new RuntimeException("提示: 令牌无效,无效token!");
                //4.存储到当前请求的上下文中
                request.setAttribute("token", token);
                request.setAttribute("user", o);
            }
        }
        return true;
    }
}
